package com.spzx.auth.controller;

import com.spzx.auth.form.LoginBody;
import com.spzx.auth.form.RegisterBody;
import com.spzx.auth.service.H5TokenService;
import com.spzx.auth.service.SysRecordLogService;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.utils.JwtUtils;
import com.spzx.common.security.auth.AuthUtil;
import com.spzx.common.security.service.TokenService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.system.api.model.LoginUser;
import com.spzx.user.api.domain.UserInfo;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * projectName: spzx-parent
 *
 * @author: 王宝贵
 * time: 2024/10/12 20:23 周六
 * description: 用户注册
 */
@RestController
@Slf4j
public class H5TokenController {

    @Autowired
    private H5TokenService h5TokenService;

    @Autowired
    private TokenService tokenService;


    //用户注册
    @PostMapping("/h5/register")
    public R<?> register(@RequestBody RegisterBody registerBody) throws ServletException {
        h5TokenService.register(registerBody);
        return R.ok();
    }

    //用户登陆
    @PostMapping("/h5/login")
    public R<?> login(@RequestBody LoginBody form){
        LoginUser loginUser = h5TokenService.login(form.getUsername(),form.getPassword());
        //返回的是token令牌
        return R.ok(tokenService.createToken(loginUser));
    }

    //用户退出
    @DeleteMapping("/h5/logout")
    public R<?> logout(HttpServletRequest request){
        String token = SecurityUtils.getToken(request);
        if(token.isEmpty()){
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            //sysLoginService.logout(username);
        }
        return R.ok();
    }

}